package com.example.mobilesafe.service;

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;


public class LocationService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        // 获取手机的经纬度坐标
        // 1.获取位置管理者对象
        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        // 2.以最优的方式获取经纬度
        Criteria criteria = new Criteria();
        criteria.setCostAllowed(true); // 允许使用流量
        criteria.setAccuracy(Criteria.ACCURACY_FINE); // 指定获取经纬度的精确度
        String bestProvider = lm.getBestProvider(criteria, true);
        // 3.在一定时间间隔，移动一定距离后获取经纬度坐标，注意动态申请权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        lm.requestLocationUpdates(bestProvider, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 经度
                double longitude = location.getLongitude();
                // 纬度
                double latitude = location.getLatitude();

                // 4.发送短信给另一台手机进行报警
                SmsManager sms = SmsManager.getDefault();
                sms.sendTextMessage("5556",null,"longtituede change!!" + longitude,null,null);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // GPS状态发生切换的事件监听
            }

            @Override
            public void onProviderEnabled(String provider) {
                // GPS开启的时候的事件监听
            }

            @Override
            public void onProviderDisabled(String provider) {
                // GPS关闭的时候的事件监听
            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}